package emulator.hardware.io.peripherals.iec.sim;

import java.util.LinkedList;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class MachineState
{
	static Logger logger = LogManager.getLogger(MachineState.class.getName());
	private String _name;
	private List<Edge> _edges = new LinkedList<Edge>();

	public MachineState(String name)
	{
		_name = name;
	}
	
	public String getName()
	{
		return _name;
	}
	
	public MachineState next() throws Exception
	{
		try
		{
			for (Edge edge : _edges)
			{
				if (edge.isActive())
					return edge.execute();
			}
		}
		catch (Exception ex)
		{
			logger.error("Failed to handle state " + getName(), ex);
			throw ex;
		}
		return this;
	}
	
	public MachineState addEdge(Event event, Action action, MachineState nextState)
	{
		_edges.add(new Edge(event, action, nextState));
		return this;
	}

	public MachineState enter()
	{
		return this;
	}
}
